"ui";
activity.window.addFlags(android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.window.setStatusBarColor(android.graphics.Color.TRANSPARENT);
activity.window.getDecorView().setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE | android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
var oneAppRunTime;

ui.layout(
    <vertical>
        <linear id="appbar" orientation="vertical" h="75">
            <View h="25" w="*"/>
            <frame h="50">
                <img id="back" src="@drawable/ic_arrow_back_black_48dp" padding="12" tint="#ffffff" w="50" h="50" foreground="?selectableItemBackground"/>
                <text id="app_name" textSize="18sp" textStyle="bold" textColor="#ffffff" w="*" text="视频助手" h="50" gravity="center"/>
            </frame>
        </linear>
        <frame h="*">
            <vertical>
                <list id="run_list">
                    <vertical>
                        <linear orientation="horizontal" w="*" h="30" margin="5 5 5 0">
                            <img src="{{app_icon}}" radius="5" w="30" h="30" padding="3dp" foreground="?selectableItemBackground" />
                            <text id="app_name" textSize="16sp" marginLeft="5" textColor="black" text="{{app_name}}" h="30" gravity="center_vertical"/>
                        </linear>
                        <View w="*" h="1" bg="#E0E0E0" margin="0 5 0 0"/>
                    </vertical>
                </list>
                <vertical id="start_params" visibility="gone">
                    <View w="*" h="10" bg="#f4f5f6" />
                    <View w="*" h="1" bg="#E0E0E0" />

                    <horizontal h="40" margin="10 0 10 0">
                        <text textSize="14sp" textColor="black" text="App启动等待时间" w="0" h="40" gravity="center_vertical" layout_weight="1"/>
                        <input id="startWaitTime" textSize="14sp" textColor="black" inputType="number" w="120" h="40"  text="8" hint="8" padding="10 0 0 0" />
                        <text textSize="14sp"  text="秒" textColor="black"  w="auto" h="40"/>
                    </horizontal>

                    <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E0E0E0'></horizontal>

                    <horizontal h="40" margin="10 0 10 0">
                        <text textSize="14sp" textColor="black" text="单个App运行时间" w="auto" h="40" gravity="center_vertical" layout_weight="1"/>
                        <input id="oneAppRunTime" textSize="14sp" textColor="black" inputType="number" w="120" h="40"  text="40" hint="0" padding="10 0 0 0" />
                        <text textSize="14sp"  text="分" textColor="black"  w="auto" h="40"/>
                    </horizontal>

                    <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E0E0E0'></horizontal>

                    <horizontal h="40" margin="10 0 10 0">
                        <text textSize="14sp" textColor="black" text="程序每日执行次数" w="auto" h="40" gravity="center_vertical" layout_weight="1"/>
                        <input id="everydayNumber" textSize="14sp" textColor="black" inputType="number" w="120" h="40"  text="4" hint="0" padding="10 0 0 0" />
                        <text textSize="14sp"  text="轮" textColor="black"  w="auto" h="40"/>
                    </horizontal>

                    <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E0E0E0'></horizontal>
                    <horizontal h="40" margin="10 0 10 0">
                        <Switch textSize="14sp" textColor="black" id="random_up"  text="视频随机点赞(10%)" checked="true" layout_weight="1" h="40"/>
                    </horizontal>
                    
                    <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E0E0E0'></horizontal>
                    <horizontal h="40" margin="10 0 10 0">
                        <Switch textSize="14sp" textColor="black" id="auto_refresh"  text="随机时间重新获取视频" checked="true" layout_weight="1" h="40"/>
                    </horizontal>
                    <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E0E0E0'></horizontal>

                    <horizontal h="40" margin="10 0 10 0">
                        <Switch textSize="14sp" textColor="black" id="auto_up_down"  text="自动上滑、下滑" checked="true" layout_weight="1" h="40"/>
                    </horizontal>
                    <horizontal w="*" h="1sp" margin="0 5 0 5" bg='#E0E0E0'></horizontal>
                    <horizontal w="*" margin="0 40 0 20" gravity="center">
                        <button id="runSrt" text="开始运行" w="240sp" textColor="#FFFFFF" gravity="center" textSize="15sp" />
                    </horizontal>
                </vertical>
                <vertical id="error_404" visibility="gone">
                    <vertical padding="25">
                        <linear orientation="horizontal" gravity="left" marginTop="10">
                            <img src="@drawable/ic_warning_black_48dp" tint="red" h="30"/>
                            <text id="Statuscode" text="404" textStyle="bold" textSize="22" textColor="red"/>
                        </linear>
                        <text id="tip" text="请求错误！" textStyle="bold" textSize="18" margin="0 5 0 5" textColor="#000000"/>
                        <text id="tips" text="这可能是一个严重的服务器端的错误，请先检查您的网络配置是否正确，若多次出现此错误请联系开发者。" textSize="14" margin="0 0 30 0" textColor="#000000"/>
                    </vertical>
                </vertical>
            </vertical>
        </frame>
    </vertical>
);
ui.appbar.backgroundDrawable = GradientDrawable("LEFT_RIGHT", ["#FF0081FF", "#FF1CBBB4"]);
ui.runSrt.backgroundDrawable = GradientDrawable("LEFT_RIGHT", ["#FF0081FF", "#FF1CBBB4"]);
/**
 * 转换成系统支持的颜色
 * @param {颜色} color 
 */
function Color(color) {
    return android.graphics.Color.parseColor(color);
}

/**
 * 配置渐变色
 * @param {方向} orientation 
 * @param {颜色数组} color 
 */
function GradientDrawable(orientation, color) {
    var colors = [];
    color.forEach(color => colors.push(Color(color)));
    return new android.graphics.drawable.GradientDrawable(android.graphics.drawable.GradientDrawable.Orientation[orientation], colors);
}

ui.back.on("click",function(){
    ui.finish();
});

threads.start(initDatas);
var num = 0;
let list = JSON.parse("[]");
var storage = storages.create("video_app");

function initDatas(){
    //等待数据获取完成后在展示部分UI
    var Url = "https://gitee.com/wupk/auto.test/raw/master/test/dats.json";
    var res_script = http.get(Url, {
        headers: {
            'Accept-Language': 'en-us,en;q=0.5',
            'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11'
        }
    });
    var temp = res_script.body.string();
    if (res_script.statusCode == 200){
        let json = JSON.parse(temp);
        var t = 0;
        for(var i=0;i<json.length;i++){
            var check = storage.get(json[i].app_package, false);
            if(check){
                list[t] = json[i];
                t++;
            }
        }
        //获取到数据以后重新计算一下app是否安装，和已经缓存的数据，缓存的数据放到最上方
        ui.post(function(action, delay){
            setDatas(list);
        });
    }else{
        ui.error_404.visibility = 0x8;
    }
}

function setDatas(json){
    ui.run_list.setDataSource(json);
    ui.start_params.visibility = 0x0;
}

/**
 * 格式化时间
 */
function getTime() {
    var fmt = "YYYY-MM-dd hh:mm:ss";
    var d = new Date();
    var hh = d.getHours();
    var mm = d.getMinutes();
    if (mm < 30) {
        mm = 30
    } else {
        hh += 1;
        mm = 0
    }
    var o = {
        "Y+": d.getYear() + 1900,
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "h+": hh,
        "m+": mm,
        "s+": 0
    };
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 4) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    fmt = fmt.replace(/-/g, '/');
    return fmt;
}

// 获取时分秒用于记录日志
function logCommon(msg) {
    console.log(formatDate(getNow()) + " " + msg);
}
function logInfo(msg) {
    console.info(formatDate(getNow()) + " " + msg);
}
function logWarn(msg) {
    console.warn(formatDate(getNow()) + " " + msg);
}
function logError(msg) {
    console.error(formatDate(getNow()) + " " + msg);
}

// 时间戳转时间字符串
function add0(m) {
    return m < 10 ? '0' + m : m
}
// 根据时间偏移值计算真实时间
function getNow() {
    var now = new Date().getTime();
    return now;
}
function add00(m) {
    if (m < 10) {
        return '00' + m;
    } else if (m < 100) {
        return '0' + m;
    } else {
        return m;
    }
}

function formatDate(needTime) {
    //needTime是整数，否则要parseInt转换
    var time = new Date(parseInt(needTime));
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return add0(h) + ':' + add0(mm) + ':' + add0(s);
}

setTimeout(initConfig, 500);

function initConfig() {
    startWaitTime = storage.get("startWaitTime", "8");
    oneAppRunTime = storage.get("oneAppRunTime", "30");
    everydayNumber = storage.get("everydayNumber","4");

    ui.startWaitTime.setText(startWaitTime);
    ui.oneAppRunTime.setText(oneAppRunTime);
    ui.everydayNumber.setText(everydayNumber);

    //随机点赞、随机刷新
    ui.random_up.checked = storage.get("random_up", true);
    ui.auto_refresh.checked = storage.get("auto_refresh", true);
    ui.auto_up_down.checked = storage.get("auto_up_down", true);
}

// 程序主要逻辑
ui.runSrt.click(function () {
    // 检查无障碍服务
    //  if (auto.service == null) {
    //      toast("请先开启无障碍服务！");
    //      return;
    //  }
    //运行
    storage.put("startWaitTime", ui.startWaitTime.getText().toString());
    storage.put("oneAppRunTime", ui.oneAppRunTime.getText().toString());
    storage.put("everydayNumber", ui.everydayNumber.getText().toString());

    storage.get("random_up", ui.random_up.isChecked());
    storage.get("auto_refresh", ui.auto_refresh.isChecked());
    storage.get("auto_up_down", ui.auto_up_down.isChecked());

    if (ui.runSrt.getText().toString() === '开始运行') {
        // 一直保持屏幕常亮
        device.keepScreenOn();
        threads.start(main);
        ui.runSrt.setText('停止运行');
    } else {
        threads.shutDownAll();
        console.hide();
        device.cancelKeepingAwake();
        ui.runSrt.setText('开始运行');
    }
});

var num_ = 1;
//是否开启滑动模式，已经开启不在开启，保证之开启一次，避免冲突
var is_start_slide = false;
//程序已经执行次数
var run_num = 1;
var start_run_time;
var end_run_time;
var app_status = "0";
/**
 * 主函数
 */
function main(){
    //显示控制台
    var middle = device.width / 2 - 400;
    console.setSize(800, 800);
    console.setPosition(middle, 100);
    console.show();

    var everyday_num = parseInt(everydayNumber);
    var app_name = "";
    for(var i=0;i<list.length;i++){
        app_name+=list[i].app_name+"、";
        list[i].run_tag = true;
    }
    logError("本次执行的APP："+app_name);

    //程序启动时间,不可修改
    var startTime = new Date().getTime();
    //计算程序结束时间，到达结束时间后重新初始化参数
    var end_time  = new Date( startTime + oneAppRunTime * list.length * 60 * 1000).getTime();
    
    setInterval(function(){
        for (var i = 0; i < list.length; i++) {

            var nowTime = new Date().getTime();
            var endTime = new Date(startTime.valueOf() + oneAppRunTime * i * 60 *  1000).getTime();
            var nextTime = new Date(startTime.valueOf() + oneAppRunTime * (i+1) * 60  * 1000).getTime();

            if(nowTime>=endTime && nowTime<= nextTime){
                if(list[i].run_tag){
                    list[i].run_tag = false;
                    logInfo("启动："+list[i].app_name);

                    start_run_time = "4";
                    end_run_time = "8";
                    
                    app.launchPackage(list[i].app_package);
                    threads.start(stratRun);
                }
            }

            if(nowTime>=end_time){
                startTime = nowTime;
                run_num++;
                end_time = new Date( nowTime.valueOf() + oneAppRunTime * list.length * 60 * 1000).getTime();
                //完成一次任务后，将list里的数据重新初始化，否则不会在开启其他app继续执行任务
                
                for(var i=0;i<list.length;i++){
                    list[i].run_tag = true;
                }
            }

            if(run_num > everyday_num){
                logInfo("已经到达执行次数，停止运行...");
                threads.shutDownAll();
                console.hide();
                device.cancelKeepingAwake();
                ui.runSrt.setText('开始运行');
            }
        }
    },1000);
}

/**
 * 开启滑动模式
 * 单独线程
 */
function stratRun(){

    if(!is_start_slide){
        is_start_slide = true;

        setInterval(function(){
            huadong();
            autopage();
        },1000);
    }
}


/**
 * 滑动模式
 */
function huadong(){
    //随机等待时间random（最小值，最大值）根据需要更改数值（单位秒）
    var time_random=random(parseInt(start_run_time)*1000,parseInt(end_run_time)*1000);
    //version 1.0
    // swipe(device.width/2+200,device.height-200 ,device.width/2,height_2,duration);
    var height = parseInt(device.height);
    var width = parseInt(device.width);
    //version 1.1

    var x1 = width/2+random(100,200);
    var y1 = height-random(50,300);
    var y2 = random(100,150);
    
    if(ui.auto_up_down.isChecked()){
        var sjs = random(1,100);
        if(sjs>30){//随机上滑
            var x2 = width/2 + random(50,120);
            var y2 = random(80,180);
            randomSwipe(x2,height-200 ,x2,y2);
        }else{//随机下滑
            var x2 = random(50,120);
            var d = random(200, 320)
            swipe(x2,150, x2,height-200 ,d);
        }
    }else{
        randomSwipe(x1,y1 , x1,y2);
    }

    logInfo("总浏览视频: "+num_+"次 ~ "+time_random);
    num_++;

    if(ui.random_up.isChecked()){
        var r = random(4000,8000);
        //400/4000  1/10
        if(r<6000){
            logInfo("执行 【随机点赞】 事件...");
            //经软件判断在屏幕左下2/3处执行双击点赞事件最合理，不会有
            var dz_x1 = 100 + random(80,180);
            var dz_y1 = height*2/3 + random(80,180);
            click(dz_x1,dz_y1);
            sleep(200)
            click(dz_x1,dz_y1);
        }
    }

    sleep(time_random);
}

/**
 * 自动检测页面内容
 */
function autopage(){
    if(className("android.widget.Button").text("继续看视频").exists()){
        className("android.widget.Button").text("继续看视频").findOnce().click();
        logInfo("执行 【继续看视频】 事件...");
    }
    if(className("android.widget.TextView").text("点击进入直播间").exists()){
        logInfo("当前视频是直播，直接跳过...");
        swipe(random(80,180),device.height-200 ,random(80,180),150,200);
    }
    if(className("android.widget.TextView").text("点击打开图集").exists()){
        logInfo("当前视频是图片，直接跳过...");
        swipe(random(80,180),device.height-200 ,random(80,180),150,200);
    }
    if(className("android.widget.TextView").text("点击打开长图").exists()){
        logInfo("当前视频是图片，直接跳过...");
        swipe(random(80,180),device.height-200 ,random(80,180),150,200);
    }

    if(className("android.view.View").text("立即签到").exists()){
        className("android.view.View").text("立即签到").findOnce().click();
        logInfo("执行 【立即签到】 事件...");
    }

    if(id("btn_confirm").exists()){
        //刷宝短视频，直播任务
        var dz_x1 = 100 + random(80,180);
        var dz_y1 = height*2/3 + random(80,180);
        click(dz_x1,dz_y1);
    }

    if(id("btn_close").exists()){
        id("btn_close").click();
    }

    if(id("iv_close").exists()){
        id("iv_close").click();
    }
    
}

/**
 * 真人模拟滑动函数
 *
 * 传入值：起点终点坐标
 * 效果：模拟真人滑动
 */
function randomSwipe(sx, sy, ex, ey) {
    //设置控制点极限距离
    var leaveHeightLength = 300

    //根据偏差距离，应用不同的随机方式
    var my = (sy + ey) / 2
    var y2 = my + random(0, leaveHeightLength)
    var y3 = my - random(0, leaveHeightLength)

    var lx = (sx - ex) / 3
    if (lx < 0) { lx = -lx }
    var x2 = sx + lx / 2 + random(0, lx)
    var x3 = sx + lx + lx / 2 + random(0, lx)

    //获取运行轨迹，及参数
    var time = [0, random(200, 450)]
    var track = bezierCreate(sx, sy, x2, y2, x3, y3, ex, ey)
    gestures(time.concat(track))
}

/**
 * 获取滑动坐标组
 * @param {*} x1
 * @param {*} y1
 * @param {*} x2
 * @param {*} y2
 * @param {*} x3
 * @param {*} y3
 * @param {*} x4
 * @param {*} y4
 */
function bezierCreate(x1, y1, x2, y2, x3, y3, x4, y4) {
    //构建参数
    var h = 100;
    var cp = [{ x: x1, y: y1 + h }, { x: x2, y: y2 + h }, { x: x3, y: y3 + h }, { x: x4, y: y4 + h }];
    var numberOfPoints = 100;
    var curve = [];
    var dt = 1.0 / (numberOfPoints - 1);

    //计算轨迹
    for (var i = 0; i < numberOfPoints; i++) {
        var ax, bx, cx;
        var ay, by, cy;
        var tSquared, tCubed;
        var result_x, result_y;

        cx = 3.0 * (cp[1].x - cp[0].x);
        bx = 3.0 * (cp[2].x - cp[1].x) - cx;
        ax = cp[3].x - cp[0].x - cx - bx;
        cy = 3.0 * (cp[1].y - cp[0].y);
        by = 3.0 * (cp[2].y - cp[1].y) - cy;
        ay = cp[3].y - cp[0].y - cy - by;

        var t = dt * i
        tSquared = t * t;
        tCubed = tSquared * t;
        result_x = (ax * tCubed) + (bx * tSquared) + (cx * t) + cp[0].x;
        result_y = (ay * tCubed) + (by * tSquared) + (cy * t) + cp[0].y;
        curve[i] = {
            x: result_x,
            y: result_y
        };
    }

    //轨迹转路数组
    var array = [];
    for (var i = 0; i < curve.length; i++) {
        try {
            var j = (i < 100) ? i : (199 - i);
            xx = parseInt(curve[j].x)
            yy = parseInt(Math.abs(100 - curve[j].y))
        } catch (e) {
            break
        }
        array.push([xx, yy])
    }

    return array
}